package redemo;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 死锁排查
 * 怎么证明是死锁，不是死循环。
 *
 * 要拿证据说话，有理有据
 */
public class DeadLockDemo {
    private String lock1 = null;
    private String lock2 = null;

    public DeadLockDemo(String lock1, String lock2) {
        this.lock1 = lock1;
        this.lock2 = lock2;
    }

    public void acquireLock(String lock1, String lock2) {
        synchronized (lock1) {
            System.out.println(Thread.currentThread().getName() + "占有" + lock1 + "\t 准备申请" + lock2);
            try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }

            synchronized (lock2) {
                System.out.println(Thread.currentThread().getName() + "成功申请" + lock2);
            }
        }
    }

    public static void main(String[] args) {
        String lock1 = "lock1";
        String lock2 = "lock2";
        DeadLockDemo source = new DeadLockDemo(lock1, lock2);
        new Thread(() -> { source.acquireLock(lock1, lock2); }).start();
        new Thread(() -> { source.acquireLock(lock2, lock1); }).start();
    }
}
